//
//  NewsListUISegmentedView.m
//  ShowYork
//
//  Created by hxh on 2021/1/18.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "NewsListSegmentedView.h"
#import "NewsListSegmentedItemCell.h"

typedef void(^doneBlock)(NSInteger index);


@interface NewsListSegmentedView ()
@property (nonatomic,copy)doneBlock done;
@property (nonatomic,strong)UIScrollView *scrollView;

@property (nonatomic,strong)NSMutableArray *imgArray;
@property (nonatomic,strong)NSMutableArray *lbArray;
@property (nonatomic,strong)NSMutableArray *btnArray;

@property (nonatomic,strong)UIButton *lastBtn;

@property (nonatomic,assign)CGPoint lastContentViewContentOffset;

@end

@implementation NewsListSegmentedView

- (NSMutableArray *)btnArray{
    if (!_btnArray) {
        _btnArray = [NSMutableArray array];
    }
    return _btnArray;
}

-(NSMutableArray *)imgArray{
    if (!_imgArray) {
        _imgArray = [NSMutableArray array];
    }
    return _imgArray;
}
-(NSMutableArray *)lbArray{
    if (!_lbArray) {
        _lbArray = [NSMutableArray array];
    }
    return _lbArray;
}

- (instancetype)initWithCompleteBlock:(void (^)(NSInteger))completeBlock{
    return [self initWithTitleArray:@[] completeBlock:completeBlock];
}
- (instancetype)initWithTitleArray:(NSArray <NewsTagItemModel *>*)itemArray completeBlock:(void (^)(NSInteger))completeBlock{

    if (self = [super init]) {
        _itemArray = itemArray;
        [self setUI];
        if (completeBlock) {
            self.done = ^(NSInteger index) {
                completeBlock(index);
            };
        }
    }
    return self;
}

- (void)setUI{
    
    _currentIndex = 0;
    
    self.frame = CGRectMake(0, 0, kScreenW, 44);

    self.scrollView = [[UIScrollView alloc]initWithFrame:self.frame];
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    
    [self addSubview:self.scrollView];
}




- (void)setCurrentIndex:(NSInteger)currentIndex{
    _currentIndex = currentIndex;
    UIButton *btn = self.btnArray[currentIndex];
    if (btn == self.lastBtn) return;
    
    
    CGPoint cellCenter = btn.center;
   
    CGFloat scrollx = cellCenter.x - self.scrollView.cl_width * 0.5;
    if (scrollx < 0) {
        scrollx = 0;
    }
    
    if (self.scrollView.contentSize.width - self.scrollView.cl_width < 0) {
        scrollx = 0;
    }else{
        if (scrollx > self.scrollView.contentSize.width - self.scrollView.cl_width) {
            scrollx = self.scrollView.contentSize.width - self.scrollView.cl_width + 16;
        }
    }
    [self.scrollView setContentOffset:CGPointMake(scrollx, 0) animated:YES];
    

    UIImageView *lastImgView = self.imgArray[self.lastBtn.tag];
    lastImgView.hidden = YES;
    
    UILabel *lb = self.lbArray[self.lastBtn.tag];
    lb.textColor = C153;
    
    UIImageView *currentImgView = self.imgArray[btn.tag];
    currentImgView.hidden = NO;
    
    UILabel *currentLb = self.lbArray[btn.tag];
    currentLb.textColor = RGBA(238, 157, 59, 1);
    
    self.lastBtn = btn;

}


- (void)setItemArray:(NSArray<NewsTagItemModel *> *)itemArray{
    
    
    [itemArray enumerateObjectsUsingBlock:^(NewsTagItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx == 0) {
            obj.isSelected = YES;
        }
    }];
    _itemArray = itemArray;
  
    __block CGFloat maxWidth = 0;
    
    CGFloat paddingLeft = 21.0f;
    
    CGFloat paddingRight = 20.0f;
    
    CGFloat margin = 11;
    
    CGFloat titleMargin = 6.0f;
    
    // 判断所有内容的长度
    [self.itemArray enumerateObjectsUsingBlock:^(NewsTagItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        CGSize size = [RPAppManager getTextSizeWithText:obj.newsTagName font:[UIFont boldSystemFontOfSize:14] maxSize:CGSizeMake(kScreenW, MAXFLOAT)];
        
        maxWidth = maxWidth + floor(size.width) + 2 * margin;
    }];

    
    if (maxWidth + paddingLeft + paddingRight + (self.itemArray.count - 1)*titleMargin <= kScreenW) {
        
        CGFloat newPadding = (kScreenW - maxWidth - (self.itemArray.count - 1) * titleMargin)/2;
        __block UIView *lastView = nil;
        [self.itemArray enumerateObjectsUsingBlock:^(NewsTagItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CGSize size = [RPAppManager getTextSizeWithText:obj.newsTagName font:[UIFont boldSystemFontOfSize:14] maxSize:CGSizeMake(kScreenW, MAXFLOAT)];
            
//            UIImage *image = [UIImage imageNamed:@"news_bg_tag"];
//            image = [image stretchableImageWithLeftCapWidth:floorf(image.size.width/2) topCapHeight:floorf(image.size.height/2)];
            
            UIImageView *bgImgView = [[UIImageView alloc]init];
            bgImgView.backgroundColor = RGBA(238, 157, 59, 0.2);
            bgImgView.layer.cornerRadius = 12;
            bgImgView.layer.masksToBounds = YES;
            bgImgView.hidden = idx > 0;
            [self.scrollView addSubview:bgImgView];
            
            UILabel *lb = [[UILabel alloc]init];
            lb.textColor = idx == 0?RGBA(238, 157, 59, 1):C153;
            lb.font = [UIFont boldSystemFontOfSize:14];
            lb.text = obj.newsTagName;
            [self.scrollView addSubview:lb];
            
            
            UIButton *btn = [[UIButton alloc]init];
            btn.tag = idx;
            [btn addTarget:self action:@selector(covertMethod:) forControlEvents:UIControlEventTouchUpInside];
            [self.scrollView addSubview:btn];
            
            
            if (lastView == nil) {
                [bgImgView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(self.scrollView);
                    make.left.equalTo(self.scrollView).offset(newPadding);
                    make.width.mas_equalTo(size.width + 2 * margin);
                    make.height.mas_equalTo(24);
                }];
            }else{
                [bgImgView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(self.scrollView);
                    make.width.mas_equalTo(size.width + 2 * margin);
                    make.left.equalTo(lastView.mas_right).offset(titleMargin);
                    make.height.mas_equalTo(24);
                }];
            }
            [lb mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(bgImgView);
            }];
            
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.left.right.equalTo(bgImgView);
            }];
            
            lastView = bgImgView;
            
            
            [self.imgArray addObject:bgImgView];
            [self.lbArray addObject:lb];
            [self.btnArray addObject:btn];
        }];
    }else{
        
        
        [self.scrollView setContentSize:CGSizeMake(maxWidth + paddingLeft + paddingRight + (self.itemArray.count - 1)*titleMargin, 0)];
        
        __block UIView *lastView = nil;
        [self.itemArray enumerateObjectsUsingBlock:^(NewsTagItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CGSize size = [RPAppManager getTextSizeWithText:obj.newsTagName font:[UIFont boldSystemFontOfSize:14] maxSize:CGSizeMake(kScreenW, MAXFLOAT)];
            UIImageView *bgImgView = [[UIImageView alloc]init];
            bgImgView.backgroundColor = RGBA(238, 157, 59, 0.2);
            bgImgView.layer.cornerRadius = 12;
            bgImgView.hidden = idx > 0;
            bgImgView.tag = idx;
            [self.scrollView addSubview:bgImgView];
            
            UILabel *lb = [[UILabel alloc]init];
            lb.textColor = idx == 0?RGBA(238, 157, 59, 1):C153;
            lb.font = [UIFont boldSystemFontOfSize:14];
            lb.text = obj.newsTagName;
            [self.scrollView addSubview:lb];
            
            UIButton *btn = [[UIButton alloc]init];
            btn.tag = idx;
            [btn addTarget:self action:@selector(covertMethod:) forControlEvents:UIControlEventTouchUpInside];
            [self.scrollView addSubview:btn];
            
          
            
            if (lastView == nil) {
                [bgImgView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(self.scrollView);
                    make.left.equalTo(self.scrollView).offset(paddingLeft);
                    make.width.mas_equalTo(size.width + margin * 2);
                    make.height.mas_equalTo(24);
                }];
            }else{
                [bgImgView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(self.scrollView);
                    make.width.mas_equalTo(size.width + margin * 2);
                    make.left.equalTo(lastView.mas_right).offset(titleMargin);
                    make.height.mas_equalTo(24);
                }];
            }
            
            [lb mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(bgImgView);
            }];
            
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.bottom.left.right.equalTo(bgImgView);
            }];
            lastView = bgImgView;
            
            [self.imgArray addObject:bgImgView];
            [self.lbArray addObject:lb];
            [self.btnArray addObject:btn];
        }];
        
    }
}


- (void)covertMethod:(UIButton *)btn{

    self.lastBtn = btn;
    
    if (btn.tag == self.currentIndex) {
        return;
    }
    
    CGPoint cellCenter = btn.center;
   
    CGFloat scrollx = cellCenter.x - self.scrollView.cl_width * 0.5;
    if (scrollx < 0) {
        scrollx = 0;
    }
    
    if (self.scrollView.contentSize.width - self.scrollView.cl_width < 0) {
        scrollx = 0;
    }else{
        if (scrollx > self.scrollView.contentSize.width - self.scrollView.cl_width) {
            scrollx = self.scrollView.contentSize.width - self.scrollView.cl_width + 16;
        }
    }
    [self.scrollView setContentOffset:CGPointMake(scrollx, 0) animated:YES];
    

    if (btn.tag != self.currentIndex) {
    
        
        UIImageView *lastImgView = self.imgArray[self.currentIndex];
        lastImgView.hidden = YES;
        
        UILabel *lb = self.lbArray[self.currentIndex];
        lb.textColor = C153;
        
        UIImageView *currentImgView = self.imgArray[btn.tag];
        currentImgView.hidden = NO;
        
        UILabel *currentLb = self.lbArray[btn.tag];
        currentLb.textColor = RGBA(238, 157, 59, 1);

        _currentIndex = btn.tag;

        if (self.done) {
            self.done(btn.tag);
        }
    }
}

- (void)setContentScrollView:(UIScrollView *)contentScrollView{
    if (_contentScrollView != nil) {
        [_contentScrollView removeObserver:self forKeyPath:@"contentOffset"];
    }
    _contentScrollView = contentScrollView;
    self.contentScrollView.scrollsToTop = NO;
    [self.contentScrollView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"contentOffset"]) {
        CGPoint contentOffset = [change[NSKeyValueChangeNewKey] CGPointValue];
    
        if ((self.contentScrollView.isTracking || self.contentScrollView.isDecelerating)) {
           
            CGFloat ratio = contentOffset.x/self.contentScrollView.bounds.size.width;
            NSInteger baseIndex = floorf(ratio);
            CGFloat remainderRatio = ratio - baseIndex;
        
            if (remainderRatio == 0) {
                if (!(self.lastContentViewContentOffset.x == contentOffset.x && self.currentIndex == baseIndex)) {
                    self.currentIndex = baseIndex;
                }
            }
        }
        self.lastContentViewContentOffset = contentOffset;
    }
}
- (void)dealloc{
    if (self.contentScrollView) {
        [self.contentScrollView removeObserver:self forKeyPath:@"contentOffset"];
    }
}


@end
